const {md5} = require("./base-crypto") ;
const {findFirst} = require("./base-database") ;
const jwt = require("./jwt-simple");
const User = uniCloud.database().collection("uni-id-users");

/**
 * 获取客户端User-Agent
 */
function getClientUaHash () {
	const hashContent = /MicroMessenger/i.test(__ctx__.CLIENTUA) ? __ctx__.CLIENTUA.replace(/(MicroMessenger\S+).*/i, '$1') : __ctx__.CLIENTUA
    return md5(hashContent);
}

module.exports = {
	
	checkToken : async function ( token , config ) {
		try {
		  const payload = jwt.decode(token, config.tokenSecret ) ;
		  if ( config.bindTokenToDevice && payload.clientId !== getClientUaHash()) {
			return {
			  code: 30201,
			  msg: 'token不合法，请重新登录'
			}
		  }
		  const userInfo = findFirst(await User.doc(payload.uid).get()) ;
		  if ( null == userInfo || !userInfo.token) {
			return {
			  code: 30202,
			  msg: 'token不合法，请重新登录'
			}
		  }
		  if (userInfo.status === 1) {
			return {
			  code: 10001,
			  msg: '账号已禁用'
			}
		  }
		  let tokenList = userInfo.token
		  if (typeof tokenList === 'string') {
			tokenList = [tokenList]
		  }
		  if (tokenList.indexOf(token) === -1) {
			return {
			  code: 30202,
			  msg: 'token不合法，请重新登录'
			}
		  }

		  uniCloud.logger.log('checkToken payload', payload)

		  return {
			code: 0,
			msg: 'token校验通过',
			...payload,
			userInfo
		  }
		} catch (err) {
			console.log(err);
		  if (err.name === 'TokenExpiredError') {
			return {
			  code: 30203,
			  msg: 'token已过期，请重新登录',
			  err: err
			}
		  }

		  return {
			code: 30204,
			msg: '非法token',
			err: err
		  }
		}
	},
	
	/**
	 * 创建token
	 * @param {Object} config
	 * @param {Object} uid
	 */
	createToken : function (  uid  , config ) {
		var signContent = { uid } ;
		if (config.bindTokenToDevice) {
			var hashContent = /MicroMessenger/i.test(__ctx__.CLIENTUA) ? __ctx__.CLIENTUA.replace(/(MicroMessenger\S+).*/i, '$1') : __ctx__.CLIENTUA
		    signContent.clientId = md5(hashContent);
		}
		var token = jwt.encode( signContent, config.tokenSecret, 'HS256' , {
		  expiresIn: config.tokenExpiresIn
		});
		return {
		  token,
		  tokenExpired: Date.now() + config.tokenExpiresIn * 1000
		}
	}
}

